
var NightCaht = {}
//初始化配置文件
var option = {
	'title': '小王聊天室',
	'jsonUrl': 'json/set.json',
	'key': '',
}
var serviceState = {}
//初始化
NightCaht.init = function () {
	//init
	document.title = option.title
	NightCaht.userName = ($.fn.cookie('userName') == null)?"匿名":$.fn.cookie('userName')
	$.fn.cookie('userName', NightCaht.userName, {expires: 60*60*24*7})
	$('.message')[0].scrollTop = $('.message')[0].scrollHeight

	//读取配置文件
	NightCaht.readJson()

	
}
NightCaht.readJson = function () {
	$.ajax({
		url: option.jsonUrl,
		type: 'GET',
		dataType: 'json',
		success: function (data) {
			option = $.extend({}, option, data)
			//跟新title
			document.title = option.title
			serviceState.ok = true
			//设置心跳包
			window.setInterval(function() {NightCaht.checkState()}, 15*1000);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			// @todo需要对应的一些措施
			serviceState.ok = false
		}
	})
}
NightCaht.setUserName = function(name) {
	if(name.length > 200) {
		return false
	}
	NightCaht.userName = name
	$.fn.cookie('userName', name, {expires: 60*60*24*7})
	return true
}
NightCaht.postMessage = function (message) {
	if (!serviceState.ok) {
		return false
	};
	var postData = {
		message: message,
		op: 'push',
	}
	$.ajax({
		url: option.messageUrl,
		type: 'POST',
		data: postData,
		dataType: 'json',
		success: function (data) {

		}
	})
}
NightCaht.checkState = function() {
	$.ajax({
		url: option.stateUrl,
		type: 'get',
		dataType: 'text',
		success: function (data) {
			if (data == "ok") {
				serviceState.ok = true
			} else {
				serviceState.ok = false
				document.title = "服务器失去联系"
			}
			
		},
		error: function() {
			serviceState.ok = false
			document.title = "服务器失去联系"
		}
	})
}
NightCaht.addMessage = function (name, message, time, isMe) {
	//到最底部
	$('.message')[0].scrollTop = $('.message')[0].scrollHeight
}
NightCaht.init()